<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>键盘事件示例方向移动div</title>
    <style>
        #box1 {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
        }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            let text = document.getElementById('name');
            text.onkeydown = function (event) {
                if (event.code === 'KeyA'){
                    return false;
                }
            }
            let l = 0;
            let t = 0;
            let code = "";
            let box1 = document.getElementById('box1');
            let timer = setInterval(function() {

                if (code === "ArrowLeft") {
                    l-=10;
                    if (l <= 0) l=0;
                    box1.style.left = l +'px';
                } else if (code === "ArrowRight") {
                    l+=10;
                    box1.style.left = l +'px';
                } else if (code === "ArrowDown") {
                    t+=10;
                    box1.style.top = t+'px';
                } else if (code === "ArrowUp") {
                    t-=10;
                    if (t <= 0) t=0;
                    box1.style.top = t +'px';
                }
            },40);
            document.onkeydown = function (event) {
                event = event || window.event;
                code = event.code;
            }
        }
    </script>
</head>
<body>
<div>
    <input type="text" id="name">
    <div id="box1">

    </div>
</div>
</body>
</html>